package com.nuit.cxl.proxydemo;

import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class DynamicProxyDemo {

    class DynamicProxy implements InvocationHandler {
        private Object targetObject;

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            System.out.println("开始执行");
            Object invoke = method.invoke(targetObject, args);
            System.out.println("执行完毕");
            return invoke;
        }

        /*
            生产代理对象实例
         */
        public Object getInstance(Object targetObject){
            this.targetObject = targetObject;
            return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);
        }

    }

    @Test
    public void TestDynamicProxy(){

        System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles","true");
        List<String> list = (List) new DynamicProxy().getInstance(new ArrayList<String>());
        list.add("abc");
        System.out.println(list.getClass());
        list.remove("abc");

        List<String> list2 = new ArrayList<>();
        list2.add("abc");
        System.out.println(list2.getClass());

//        list.add("def");
    }


}
